namespace Bowlus.Common
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading;

    using Microsoft.WindowsAzure.ServiceRuntime;

    public class BowlusHostingEnvironment
    {
        public static IEnumerable<ApplicationHost> GetCurrentAppHosts()
        {
            var applicationHostRole = RoleEnvironment.Roles[Settings.AppHostRoleName];

            // We also will need to bring in the instances from the service management API to select the ones that are running
            var serviceManagementWrapper = Settings.GetManagementService();
            var deployment = serviceManagementWrapper.GetDeploymentBySlot(Settings.ServiceName, Settings.DeploymentSlot);

            var instances = from roleInstance in deployment.RoleInstanceList
                            join roleInstanceInEnvironment in applicationHostRole.Instances on roleInstance.InstanceName equals
                                roleInstanceInEnvironment.Id
                            select
                                new ApplicationHost
                                    {
                                        Status = roleInstance.InstanceStatus.Equals("Ready") ? ApplicationHostStatus.Running : roleInstance.InstanceStatus,
                                        InstanceId = roleInstanceInEnvironment.Id,
                                        ApphostHttpEndpoint = roleInstanceInEnvironment.InstanceEndpoints[Settings.AppHostHttpEndpointName].IPEndpoint,
                                        Deployments = new List<TenantDeployment>()
                                    };
            return instances;
        }

        public static void WaitTillAllAppHostsAreRunning()
        {
            while (true)
            {
                if (GetCurrentAppHosts().Count(ah => !ah.Status.Equals(ApplicationHostStatus.Running)) == 0)
                {
                    return;
                }

                BowlusLogger.LogInfo("Waiting for all apphosts to start.");
                Thread.Sleep(TimeSpan.FromSeconds(10));
            }
        }
    }
}